package com.sudichina.sudichina.view.activity.dentification;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.sudichina.sudichina.Contains;
import com.sudichina.sudichina.MyApp;
import com.sudichina.sudichina.NET.Api;
import com.sudichina.sudichina.NET.NetUtils;
import com.sudichina.sudichina.NET.onRequestDataFinish;
import com.sudichina.sudichina.R;
import com.sudichina.sudichina.bean.Car;
import com.sudichina.sudichina.bean.Result;
import com.sudichina.sudichina.utils.CarGetId;
import com.sudichina.sudichina.utils.DialogFrameAnimUtils;
import com.sudichina.sudichina.utils.StringUtils;
import com.sudichina.sudichina.utils.Toastutils;
import com.sudichina.sudichina.view.activity.main.BaseActivity;
import com.sudichina.sudichina.view.customview.xlistview.ListViewDialog;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by ${杨伟乔} on 2017/3/7.
 * 邮箱: yangweiqiao@126.com
 * QQ: 463217558
 * 别人光鲜的背后或者有着太多不为人知的痛苦
 * 学习可以改变一切、 行动可以解决一切问题、
 */
public class CarIdentificationActivity extends BaseActivity implements onRequestDataFinish {
    private static final int CHELIANG = 10011;
    private static final int XINGSHIZHENG = 10010;
    //返回键
    @BindView(R.id.btnleft)
    ImageView privateBtnleft;
    //车牌 首字母
    @BindView(R.id.tv_vehicle_first_letter)
    EditText privateTvVehicleFirstLetter;
    //车牌 6位数
    @BindView(R.id.et_number_plate)
    EditText privateEtNumberPlate;
    //车型
    @BindView(R.id.et_vehicle_model)
    TextView privateEtVehicleModel;
    //车长
    @BindView(R.id.et_vehicle_length)
    TextView privateEtVehicleLength;
    //面积
    @BindView(R.id.et_vehicle_area)
    EditText privateEtVehicleArea;
    //体积
    @BindView(R.id.et_vehicle_volume)
    EditText privateEtVehicleVolume;
    //发动机号码
    @BindView(R.id.et_engine_number)
    EditText privateEtEngineNumber;


    //照片 行驶证
    @BindView(R.id.iv_driving_license)
    ImageView privateIvDrivingLicense;
    //照片  车辆
    @BindView(R.id.iv_driver_license)
    ImageView privateIvDriverLicense;
    //提交
    @BindView(R.id.btn_save)
    Button privateBtnSave;
    private String etvehiclemodel;



    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        /**
         * 加载车辆认证的界面
         */
        setContentView(R.layout.activity_cariden_tification);
        ButterKnife.bind(this);
        //检测是否登录

        initview();
        //监测是否认证过


        try {
            Car mCar = getIntent().getParcelableExtra("mCar");
            if(mCar!=null){


                initData(mCar);

            }


        } catch (Exception e) {
        }




    }

    private void initData(Car mCar) {
//        //车型
//        TextView privateEtVehicleModel;
//        //车长
//        TextView privateEtVehicleLength;
//        //面积
//        EditText privateEtVehicleArea;
//        //体积
//        EditText privateEtVehicleVolume;
//        //发动机号码
//        EditText privateEtEngineNumber;
//        //照片 行驶证
//        ImageView privateIvDrivingLicense;
//        //照片  车辆
//        ImageView privateIvDriverLicense;

        privateTvVehicleFirstLetter.setText(mCar.getCarFirstLetter());
        privateEtNumberPlate.setText(mCar.getCardNumber());
        //        //车型
//        privateEtVehicleModel.setText();
        privateEtVehicleLength.setText(mCar.getCarLenght()+"");
        privateEtVehicleArea.setText(mCar.getCarCube()+"");
        privateEtVehicleVolume.setText(mCar.getCarWeight()+"");
        privateEtEngineNumber.setText(mCar.getEngineNum()+"");



    }




    ArrayList<String> carmodelist;
    ArrayList<String> carlength = new ArrayList<>();

    String carmode;
    String carlengths;

    private void initview() {
             /*
        标题栏
         */
        //找到控件
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        TextView toolbar_title = (TextView) findViewById(R.id.toolbar_title);
        toolbar.setTitle("");
        //设置标题
        toolbar_title.setText("车辆认证中心");
        //设置支持actionbar
        setSupportActionBar(toolbar);


    }


    @OnClick({R.id.et_vehicle_model, R.id.et_vehicle_length, R.id.btnleft, R.id.iv_driving_license, R.id.iv_driver_license, R.id.btn_save})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.et_vehicle_model:


                /*&*
                点击选择车型  弹出一个列表
                 */
                carmodelist = new ArrayList<>();
                carmodelist.add("厢式车");
                carmodelist.add("平板车");
                carmodelist.add("高低板车");
                carmodelist.add("高栏车");
                carmodelist.add("中栏车");
                carmodelist.add("低栏车");
                ListViewDialog dialog = new ListViewDialog(this, carmodelist);
                dialog.setOnonRequestFinish(new ListViewDialog.onRequestFinish() {
                    @Override
                    public void requestFinish(String s, int position) {
                        /**
                         * 获取的数据回显在控件上
                         */

                        privateEtVehicleModel.setText(s);

                    }
                });
                dialog.show();


                break;
            case R.id.et_vehicle_length:

                /**
                 * 根据选择的车型来确定车长的列表
                 */
                /**
                 * 点击选择车长
                 */

                carlength = new ArrayList<String>();


                //根据选择的车型来加载不同的车长数据

                etvehiclemodel = privateEtVehicleModel.getText().toString().trim();

                if (etvehiclemodel == null) {
                    Toastutils.showToast("请选择车型");
                    return;
                }
                if (etvehiclemodel.equals("厢式车")) {
                    carlength.clear();
                    for (int i = 0; i < Contains.XIANGSHICHE.length; i++) {

                        carlength.add(Contains.XIANGSHICHE[i] + "米");


                    }


                } else if (etvehiclemodel.equals("平板车")) {
                    carlength.clear();
                    for (int i = 0; i < Contains.PINGBANCHE.length; i++) {

                        carlength.add(Contains.PINGBANCHE[i] + "米");


                    }

                } else if (etvehiclemodel.equals("高低板车")) {
                    carlength.clear();
                    for (int i = 0; i < Contains.GAODIBANCHE.length; i++) {

                        carlength.add(Contains.GAODIBANCHE[i] + "米");


                    }

                } else if (etvehiclemodel.equals("高栏车")) {
                    carlength.clear();
                    for (int i = 0; i < Contains.GAOLANCHE.length; i++) {

                        carlength.add(Contains.GAOLANCHE[i] + "米");


                    }

                } else if (etvehiclemodel.equals("中栏车")) {
                    carlength.clear();
                    for (int i = 0; i < Contains.ZDLC.length; i++) {

                        carlength.add(Contains.ZDLC[i] + "米");


                    }

                } else if (etvehiclemodel.equals("低栏车")) {
                    carlength.clear();
                    for (int i = 0; i < Contains.ZDLC.length; i++) {

                        carlength.add(Contains.ZDLC[i] + "米");


                    }

                }


                ListViewDialog dialog1 = new ListViewDialog(this, carlength);
                dialog1.setOnonRequestFinish(new ListViewDialog.onRequestFinish() {
                    @Override
                    public void requestFinish(String s, int position) {
                        /**
                         * 获取的数据回显在控件上
                         */

                        privateEtVehicleLength.setText(s);

                        int i = carlength.indexOf(s);

                        //根据选择的车长设置面积和体积 重量
                        try {
                            String carweight = Contains.CARWEIGHT[i];
                            String carcube = Contains.CARCUBE[i]; //面积

                            privateEtVehicleArea.setText(carcube);
                            privateEtVehicleVolume.setText(carweight);
                        } catch (Exception e) {
                            privateEtVehicleArea.setText("手动输入");
                            privateEtVehicleVolume.setText("手动输入");
                        }


                    }
                });
                dialog1.show();


                break;


            case R.id.btnleft:
                finish();
                break;


            case R.id.iv_driving_license:
                //点击打开系统的相册
                makePhoto(XINGSHIZHENG);


                break;
            case R.id.iv_driver_license:
                makePhoto(CHELIANG);


                break;
            case R.id.btn_save:
                /**
                 * 点击保存 判断是不是所有的控件上有信息
                 */
//首字母
                String tvvehiclefirstletter = privateTvVehicleFirstLetter.getText().toString().trim();
                //6为数字车牌
                String etnumberplate = privateEtNumberPlate.getText().toString().trim();
//车型
                // String etvehiclemodel = privateEtVehicleModel.getText().toString().trim();
//车长
                String etvehiclelength = privateEtVehicleLength.getText().toString().trim();
                //面积
                String etvehiclearea = privateEtVehicleArea.getText().toString().trim();
//                体积
                String etvehiclevolume = privateEtVehicleVolume.getText().toString().trim();
                //发动机号码
                String etenginenumber = privateEtEngineNumber.getText().toString().trim();


                if (StringUtils.isEmpty(tvvehiclefirstletter) ||
                        StringUtils.isEmpty(etnumberplate) ||
                        StringUtils.isEmpty(etvehiclemodel) ||
                        StringUtils.isEmpty(etvehiclelength) ||
                        StringUtils.isEmpty(etvehiclearea) ||
                        StringUtils.isEmpty(etvehiclevolume) ||
                        StringUtils.isEmpty(etenginenumber)
                        ) {
                    Toastutils.showToast("请检查信息是否正确");

                    return;

                }
                System.out.println("qqq" + etvehiclemodel + etvehiclelength);
                String carId = CarGetId.getCarId(etvehiclemodel + etvehiclelength);

                System.out.println("查询的车辆id是:" + carId);

                if (carId.contains("对不起")) {
                    Toastutils.showToast("车型不存在");
                    return;
                }

                //final String url, final Map<String, String> map, Map<String, String> files, final onRequestDataFinish listener
                Map<String, Object> map = new HashMap<>();
/**
 * id :Long 车主Id （信息修改时使用）


 drivingLicensePath：驾照图片
 data.put("accountId", id);

 data.put("drivingLicense", drivingLicense);


 accountId; Long 用户Id
 carFirstLetter ：String 车牌号首字母
 cardNumber：String 车牌（6位）
 carDicId：String 车型参数对应的Id
 engineNum:String  发动机号码
 driveLicensePath    行驶证照片
 driveLicensePath2   车辆照片

 private Double carLenght;

 private Integer carCube;


 */
                map.put("accountId", String.valueOf(MyApp.getCurrentUser().getId()));


                map.put("carFirstLetter", tvvehiclefirstletter);
                map.put("cardNumber", etnumberplate);
                map.put("carDicId", carId);
                map.put("engineNum", etenginenumber);
                map.put("carWeight", etvehiclevolume);
                map.put("carCube", etvehiclearea);


                HashMap<String, String> hashMap = new HashMap<>();

                hashMap.put("driveLicensePath", driveLicensePath);
                hashMap.put("driveLicensePath2", driveLicensePath2);


                NetUtils.formPost2(Api.CARRENZHENG, map, hashMap, null, this);


                break;
        }
    }

    @Override
    public void requestdataFinish(String catalog, Object bean) {


        if (catalog.equals(Api.CARLISTBYSTATUS + MyApp.getCurrentUser().getId())) {
            // TODO: 2017/3/17 0017
            //查询状态
            Result<ArrayList<Car>> bean1 = (Result<ArrayList<Car>>) bean;
            if (bean1.getCode() == 1) {

                Intent intent = new Intent(this, CarSelectActivity.class);
                ArrayList<Car> carList = bean1.getData();

                intent.putParcelableArrayListExtra("carList",carList);

                intent.putExtra("carList", carList);
                startActivity(intent);

                finish();

            } else if (bean1.getCode() == 8015) {
                //无审核通过车辆
                //显示认证的界面
                Toastutils.showToast("请认证你的车辆:");

            }
//根据返回的状态显示界面
//如果有认证的车辆  直接显示车辆界面
//
//            else显示认证的界面


        }


        if (catalog.equals(Api.CARRENZHENG)) {
            //提交的认证信息返回数据
//            Toastutils.showToast("提交成功");
            // TODO: 2017/3/17 0017
            DialogFrameAnimUtils.startSucessAnim(getApplicationContext(), this, "提交成功");
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    startActivity(new Intent(CarIdentificationActivity.this, CarSelectActivity.class));
                    finish();
                }
            }, 2000);


        }


    }


    @Override
    public void requestdataFailed(IOException e) {

    }


    private void makePhoto(int code) {


        Intent intent;


        intent = new Intent();
                    /* 开启Pictures画面Type设定为image */
        intent.setType("image/*");
                    /* 使用Intent.ACTION_GET_CONTENT这个Action */
        intent.setAction(Intent.ACTION_GET_CONTENT);
                    /* 取得相片后返回本画面 需要带回数据  所以开启  */
        startActivityForResult(intent, code);


    }


    Bitmap bitmap = null;

    /**
     * 点击的相册和照相界面返回的数据
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            switch (requestCode) {

                case XINGSHIZHENG:  //行驶证
                    try {
                        /**
                         * 把图片传递到到界面  iv_driving_license
                         */
                        Uri originalUri = data.getData();
                        bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), originalUri);
                        privateIvDrivingLicense.setImageBitmap(bitmap);
                        driveLicensePath = getRealImagePathFromURI(getContentResolver(), originalUri);


                    } catch (Exception e) {
                        throw new RuntimeException("相册异常");

                    }
                    break;

                case CHELIANG: //车辆
                    /**
                     * 把图片传递到到界面
                     */
                    try {
                        Uri originalUri = data.getData();
                        bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), originalUri);
                        privateIvDriverLicense.setImageBitmap(bitmap);
                        driveLicensePath2 = getRealImagePathFromURI(getContentResolver(), originalUri);


                    } catch (Exception e) {
                        throw new RuntimeException("相册异常");

                    }
                    break;
            }
        }


    }

    String driveLicensePath;
    String driveLicensePath2;

    public static String getRealImagePathFromURI(ContentResolver contentResolver,
                                                 Uri contentURI) {
        Cursor cursor = contentResolver.query(contentURI, null, null, null,
                null);
        if (cursor == null)
            return contentURI.getPath();
        else {
            cursor.moveToFirst();
            int idx = cursor
                    .getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            try {
                return cursor.getString(idx);
            } catch (Exception exception) {
                return null;
            }
        }
    }


}
